package cn.rocky.offer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @version 1.0
 * @description
 * @author viki
 * @date 2021/7/22 20:36
 */
public class offer32III {

    /** Definition for a binary tree node. */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    /**
     * 第一轮从左至右,第二轮从右至左 交替
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            LinkedList<Integer> tmp = new LinkedList<Integer>();
            for (int i = queue.size(); i > 0 ; i--) {
                // 偶数层 -> 队列头部
                TreeNode node = queue.poll();
                if (list.size() % 2 == 0) {
                    tmp.addLast(node.val);
                } else {
                    // 奇数层 -> 队列尾部
                    tmp.addFirst(node.val);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            list.add(tmp);
        }
        return list;
    }


    public static void main(String[] args) {

    }

}
